# -*- coding: utf-8 -*-
"""
封装redis操作
"""
__author__ = 'shu2015626'

import time
import logging

from redis import StrictRedis
from redis.sentinel import Sentinel
from rediscluster import RedisCluster
from django.conf import settings

logger = logging.getLogger('tasks')
REDIS_SETTINGS_DCT, REDIS_MODE, REDIS_KEY_DICT = settings.REDIS_SETTINGS_DCT, settings.REDIS_MODE, settings.REDIS_KEY_DICT


class RedisOper(object):
    def __init__(self, redis_mode: str = None, redis_settings_dict: dict = None):
        redis_mode = redis_mode or REDIS_MODE
        redis_settings_dict = redis_settings_dict or REDIS_SETTINGS_DCT
        self.redis_mode = redis_mode
        if redis_mode == "single":
            passwd = redis_settings_dict.get("redis_passwd", None)
            passwd = passwd or None  # 防止password是空字符串的情况
            self.__redis_client = StrictRedis(
                host=redis_settings_dict.get("redis_host"),
                port=redis_settings_dict.get("redis_port"),
                db=redis_settings_dict.get("redis_db_num"),
                password=passwd, socket_timeout=5,
                socket_connect_timeout=5, decode_responses=True
            )
        elif redis_mode == "sentinel":
            passwd = redis_settings_dict.get("redis_passwd", None)
            passwd = passwd or None  # 防止password是空字符串的情况
            obj_sentinel = Sentinel(
                sentinels=redis_settings_dict.get('redis_sentinel_servers'),
                password=passwd, db=redis_settings_dict.get("redis_db_num"),
                socket_timeout=5, socket_connect_timeout=5, decode_responses=True
            )
            self.__redis_client = obj_sentinel.master_for(service_name=REDIS_SETTINGS_DCT.get('redis_master_name'))
        elif redis_mode == "cluster":
            passwd = redis_settings_dict.get("redis_passwd", None)
            passwd = passwd or None  # 防止password是空字符串的情况
            self.__redis_client = RedisCluster(
                startup_nodes=redis_settings_dict.get("redis_cluster_nodes"),
                password=passwd, decode_responses=True
            )
        else:
            msg = "不支持的redis模式: %s。无法创建redis实例" % str(redis_mode)
            logger.error(msg)
            raise Exception(msg)

    def _get_redis_key(self, flag: str):
        """
        获取需要操作的redis key值
        :param flag:
        :return:
        """
        return REDIS_KEY_DICT.get(flag, 'unknown')

    def get_heartbeat(self, key_flag: str = 'heartbeat'):
        """
        获取心跳值：一个时间戳
        :param key_flag: 存储心跳值的key的标识
        :return:
        """
        key = self._get_redis_key(key_flag)
        heartbeat = self.__redis_client.get(key)
        return heartbeat

    def set_heartbeat(self, key_flag: str = 'heartbeat'):
        """
        获取心跳值：一个时间戳
        :param key_flag: 存储心跳值的key的标识
        :return:
        """
        key = self._get_redis_key(key_flag)
        return self.__redis_client.set(key, time.time())


if __name__ == "__main__":
    obj_redis_oper = RedisOper("single")
